import PickerCol from './pickercol'
import transfer from '../_tool/transfer'
import { deepCopy } from '../_tool/copy'
import moment from 'moment'

export default {
  name: "Picker",
  directives: { transfer },
  props: {
    mode: String,
    format: String,
    title: String,
    value: Array,
    separator: { type: String, default: '/' },
    cascade: Boolean,
    disabled: Boolean,
    data: { type: Array, default: () => { return [] } },
    cancelText: { type: String, default: '取消' },
    okText: { type: String, default: '确定' },
    placeholder: { type: String, default: '请选择省市区' }
  },
  watch: {
    data: {
      // this.currentData = v
      // console.log('vvvv',v)
      // this.$nextTick(e => {
      //   this.setLabel()
      // })
      handler(n, p) {
        if (n != p)
          this.currentData = deepCopy(n)
        // this.$nextTick(e => {
        //   // this.setLabel()
        // })
      },
      // immediate: true,
      deep: true
    },
    value: {
      handler(n, p) {
        this.currentValue = n
        this.$nextTick(e => {
          this.setLabel()
        })
      },
      // immediate: true,
      deep: true
    }
  },
  data() {
    return {
      visible: false,
      label: '',
      labels: [],
      currentValue: [],//[].concat(this.value || ['', '', '']),
      currentData: this.data//[].concat(this.data || []),
    }
  },
  render() {
    let picker = this.currentData.map((items, index) => {
      let value = this.value[index]
      let temp = this.getIndex(items, value)
      let props = {
        ref: 'picker' + index,
        props: {
          items: items || [], value, temp,
        },
        on: {
          input: e => {
            // console.log(e)
            this.currentValue[index] = e
          },
          change: (item, i) => {
            if (item) {
              if (this.cascade && item.children) {
                this.$set(this.currentData, (index + 1), item.children)
                // this.currentData[index + 1] = item.children
                this.$nextTick(e => {
                  this.$refs['picker' + (index + 1)].scroll()
                  this.currentValue[index] = typeof item == 'object' ? item.value : item
                  this.$emit('change', item, i)
                })
              }
              this.$nextTick(e => {
                this.currentValue[index] = typeof item == 'object' ? item.value : item
                this.$emit('change', item, i)
              })
              // console.log(item, index)
              this.labels[index] = typeof item == 'object' ? item.label : item
              let label = this.getLabel(this.labels)
              if (this.mode) {
                this.label.length != label.length && (this.label = label)
              } else if (this.value && this.label.split(this.separator).length != this.labels.length) {
                this.label = label
              }
            }
          }
        }
      }
      return <PickerCol {...props} />
    })
    // let label = this.setLabel()
    let hasValue = this.value && this.value.length > 0 && this.label
    return (<div class="k-picker">
      <div class={hasValue ? 'k-picker-input' : 'k-picker-placeholder'} onClick={this.open}>{!hasValue ? this.placeholder : this.label}</div>
      <div class={'k-picker-popup ' + (this.mode == 'datetime' ? 'k-datetime-picker' : '')} v-transfer={true}>
        <transition name="k-popup-fade">
          <div class="k-picker-mask" v-show={this.visible} onClick={this.close} onTouchStart={this.stop} onTouchMove={this.stop}></div>
        </transition>
        <transition name="k-popup-slide">
          <div class="k-picker-content" v-show={this.visible}>
            <div class="k-picker-popup-header">
              <div class="k-picker-popup-left" onClick={this.cancel}>{this.cancelText}</div>
              <div class="k-picker-popup-title">{this.title}</div>
              <div class="k-picker-popup-right" onClick={this.ok}>{this.okText}</div>
            </div>
            <div class="k-picker-popup-body">
              {picker}
            </div>
          </div>
        </transition>
      </div>
    </div>
    )
  },
  mounted() {
    // this.setLabel()
  },
  methods: {
    stop(e) {
      // e.preventDefault()
      // e.stopPorpagation()
    },
    open() {
      if (this.disabled) return;
      this.visible = true
    },
    getIndex(items = [], key) {
      let current = null
      if (key === null || key === undefined || !items.length) return current;
      for (let i = 0; i < items.length; i++) {
        let value = typeof items[i] == 'object' ? items[i].value : items
        if (value == key) {
          current = i
          return i
        }
      }
      return current;
    },
    setLabel() {
      let labels = [];
      if (this.value.length > 0) {
        this.currentData.forEach((items, index) => {
          items.forEach(item => {
            let value = (typeof item == 'object') ? item.value : item
            if (this.currentValue[index] === value && value) {
              labels.push((typeof item == 'object') ? item.label : item)
            }
          })
        });
      }
      if (labels.length) {
        this.label = this.getLabel(labels)
      } else
        this.label = ''
    },
    getLabel(labels) {
      let [y, m, d, hh, mm, ss] = labels, Int = parseInt, label = '';
      // console.log(y,m,d,hh,mm,ss)
      // console.log(hh=='00',hh)
      // hh = hh == '00' ? '24' : hh
      if (this.mode == 'date') {
        if (d !== undefined) {
          let date = new Date(Int(y), Int(m) - 1, Int(d))
          label = moment(date).format(this.format)
        }
      } else if (this.mode == 'datetime') {
        if (ss !== undefined) {
          let datetime = new Date(Int(y), Int(m) - 1, Int(d), Int(hh), Int(mm), Int(ss))
          label = moment(datetime).format(this.format)
        }
      } else
        label = labels.join(` ${this.separator} `)
      return label
    },
    close() {
      this.visible = false
    },
    ok() {
      this.visible = false
      // console.log(this.currentValue)
      this.$emit('input', this.currentValue)
      this.$nextTick(e => {
        this.label = this.getLabel(this.labels)
        this.$emit('ok', this.mode ? this.label : this.labels)
      })
    },
    cancel() {
      this.visible = false
      this.$emit('cancel')
    }
  }
}